<?php
namespace app\Job;

use think\queue\Job;
use think\Db;
use think\facade\Log;
use think\facade\Cache;
use app\services\PHPExcelService;

use app\admin\model\Channelkey;

class SendNoteDo{

    public function fire(Job $job, $data){

        trace('执行批次：'.$data['id']);

        print("<info>执行批次:".$data['id']."</info>\n");

        try {

            //目标查询
            $bus_selfdom_info = Db::table('bus_selfdom_info')->where('id',$data['id'])->where('status',0)->find();
            if(!$bus_selfdom_info)
            {
                $job->delete();
                return;
            }

            $strtime = strtotime($bus_selfdom_info['send_time']) - time();

            //查询时间
            if($strtime > 0)
            {
                $job->release($strtime);
                print("<info>延迟:".$strtime."</info>\n");
                return;
            }

            $this->send_do($bus_selfdom_info,$data);

        } catch (\Exception $e) {
            trace('执行失败：'.$e->getMessage());
        }

        //如果任务执行成功后 记得删除任务，不然这个任务会重复执行，直到达到最大重试次数后失败后，执行failed方法
        $job->delete();

        // 也可以重新发布这个任务
        // $job->release($delay); //$delay为延迟时间
        print("<info>完成</info>\n");
    }

    public function send_do($bus_selfdom_info,$data)
    {
        //文件发送
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);

        $post_data = array(
                'file' => new \CURLFile(realpath($bus_selfdom_info['save_name']))
                ,'cid' => $bus_selfdom_info['channel_id']
                ,'content' => $bus_selfdom_info['sms_content']
            );

        trace("上传数据" . json_encode($post_data,JSON_UNESCAPED_UNICODE),"send");

        curl_setopt($curl, CURLOPT_URL, 'http://119.91.61.33:8080/SMS/upload/qf');

        curl_setopt($curl, CURLOPT_POST, 1 );

        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($curl, CURLOPT_USERAGENT,"TEST");

        $result = curl_exec($curl);

        trace("上传结果" . $result,"send");

        $error = curl_error($curl);

        $result = json_decode($result,true);

        //关闭URL请求
        curl_close($curl);

        if($result['code'] == 200){
            Db::table('bus_selfdom_info')->where('id',$bus_selfdom_info['id'])->update(['batch_num' => $result['order_id'],'status' => 1]);
        }else{
            trace("上传错误" . $error,"send");
        }

        return true;
    }

    public function failed($data){

    // ...任务达到最大重试次数后，失败了
    }

}